package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    private final StringRedisTemplate redisTemplate;

    @Override
    public Result queryById(Long id) {
        Shop shop = null;
        String lock = "lock:shop:" + id;
        try {
            // 从redis查询
            String key = "cache:shop:" + id;

            String shopJson = redisTemplate.opsForValue().get(key);

            // 是否存在
            if(StrUtil.isNotBlank(shopJson)){
                // 存在返回
                shop = JSONUtil.toBean(shopJson, Shop.class);
                return Result.ok(shop);
            }

            if(shopJson!=null){
                return Result.fail("店铺不存在");
            }
            boolean isLock = tryLock(lock);
            if(!isLock){
                Thread.sleep(50);
                return queryById(id);
            }

            //不存在查数据库
            shop = getById(id);
            //不存在返回错误
            if(shop == null){
                //空置写入redis
                redisTemplate.opsForValue().set(key,"",3L, TimeUnit.MINUTES);
                return Result.fail("店铺不存在");
            }
            //存在写入redis
            redisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shop),30L, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unLock(lock);
        }
        return Result.ok(shop);
    }

    @Override
    @Transactional
    public Result update(Shop shop) {


        Long id = shop.getId();

        if(id==null){

            return Result.fail("店铺id为空");
        }
        //更新数据库
        log.debug("更新数据库");
        updateById(shop);
        //删除缓存
        redisTemplate.delete("cache:shop:" + id);

        return Result.ok();
    }

    private boolean tryLock(String key){
        Boolean b = redisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(b);
    }
    private void unLock(String key){
        redisTemplate.delete(key);
    }


}
